package com.attendance.www.hr.service.impl;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.attendance.www.hr.beans.EmployeeMainBean;
import com.attendance.www.hr.constant.AppConstant;
import com.attendance.www.hr.dao.mapper.ApprovalRecordMapper;
import com.attendance.www.hr.dao.mapper.AttendanceMapper;
import com.attendance.www.hr.dao.mapper.AttendanceReportMapper;
import com.attendance.www.hr.dao.mapper.CorporationMapper;
import com.attendance.www.hr.dao.mapper.DepartmentMapper;
import com.attendance.www.hr.dao.mapper.EmployeeCorporationMapper;
import com.attendance.www.hr.dao.mapper.EmployeeDepartmentMapper;
import com.attendance.www.hr.dao.mapper.EmployeeExtMapper;
import com.attendance.www.hr.dao.mapper.EmployeeMapper;
import com.attendance.www.hr.dao.mapper.EmployeeRoleMapper;
import com.attendance.www.hr.dao.mapper.EmployeeSchedulExtMapper;
import com.attendance.www.hr.dao.mapper.EmployeeSchedulMapper;
import com.attendance.www.hr.dao.mapper.EmployeeSpecialMapper;
import com.attendance.www.hr.dao.mapper.FurloughBalanceMapper;
import com.attendance.www.hr.dao.mapper.LactationMapper;
import com.attendance.www.hr.dao.mapper.MainUsersMapper;
import com.attendance.www.hr.dao.mapper.RequestAuthorityMapper;
import com.attendance.www.hr.dao.mapper.RequestMapper;
import com.attendance.www.hr.dao.mapper.RequestReportMapper;
import com.attendance.www.hr.dao.mapper.RetroactiveMapper;
import com.attendance.www.hr.dao.mapper.RoleMapper;
import com.attendance.www.hr.dao.mapper.UserLoginMapper;
import com.attendance.www.hr.dao.mapper.UserMapper;
import com.attendance.www.hr.entitys.ApprovalRecordExample;
import com.attendance.www.hr.entitys.AttendanceExample;
import com.attendance.www.hr.entitys.AttendanceReportExample;
import com.attendance.www.hr.entitys.Corporation;
import com.attendance.www.hr.entitys.CorporationExample;
import com.attendance.www.hr.entitys.Department;
import com.attendance.www.hr.entitys.DepartmentExample;
import com.attendance.www.hr.entitys.Employee;
import com.attendance.www.hr.entitys.EmployeeCorporation;
import com.attendance.www.hr.entitys.EmployeeCorporationExample;
import com.attendance.www.hr.entitys.EmployeeDepartment;
import com.attendance.www.hr.entitys.EmployeeDepartmentExample;
import com.attendance.www.hr.entitys.EmployeeExample;
import com.attendance.www.hr.entitys.EmployeeRole;
import com.attendance.www.hr.entitys.EmployeeRoleExample;
import com.attendance.www.hr.entitys.EmployeeSchedul;
import com.attendance.www.hr.entitys.EmployeeSchedulExample;
import com.attendance.www.hr.entitys.EmployeeSpecialExample;
import com.attendance.www.hr.entitys.FurloughBalanceExample;
import com.attendance.www.hr.entitys.LactationExample;
import com.attendance.www.hr.entitys.Request;
import com.attendance.www.hr.entitys.RequestAuthorityExample;
import com.attendance.www.hr.entitys.RequestExample;
import com.attendance.www.hr.entitys.RequestReportExample;
import com.attendance.www.hr.entitys.Retroactive;
import com.attendance.www.hr.entitys.RetroactiveExample;
import com.attendance.www.hr.entitys.Role;
import com.attendance.www.hr.entitys.RoleExample;
import com.attendance.www.hr.entitys.User;
import com.attendance.www.hr.entitys.UserExample;
import com.attendance.www.hr.entitys.UserLoginExample;
import com.attendance.www.hr.service.IEmployeeMainService;
import com.attendance.www.hr.utils.ToolUtils;
import com.zhangkongli.frame.utils.MD5Util;

@Service
public class EmployeeMainServiceImpl implements IEmployeeMainService {
	@Resource
	private EmployeeMapper employeeDao;
	@Resource
	private EmployeeExtMapper employeeExtDao;
	@Resource
	private DepartmentMapper departmentDao;
	@Resource
	private RoleMapper roleDao;
	@Resource
	private CorporationMapper corporationDao;
	@Resource
	private EmployeeRoleMapper employeeRoleDao;
	@Resource
	private EmployeeDepartmentMapper employeeDepartmentDao;
	@Resource
	private EmployeeCorporationMapper employeeCorporationDao;
	@Resource
	private MainUsersMapper mainUsersDao;
	@Resource
	private UserMapper userDao;
	@Resource
	private UserLoginMapper userLoginDao;
	@Resource
	private EmployeeSchedulMapper employeeSchedulDao;
	@Resource
	private EmployeeSchedulExtMapper employeeSchedulExtDao;
	@Resource
	private EmployeeSpecialMapper employeeSpecialDao;
	@Resource
	private AttendanceMapper attendanceDao;
	@Resource
	private FurloughBalanceMapper furloughBalanceDao;
	@Resource
	private LactationMapper lactationDao;
	@Resource
	private AttendanceReportMapper attendanceReportDao;
	@Resource
	private RequestAuthorityMapper requestAuthorityDao;
	@Resource
	private RetroactiveMapper retroactiveDao;
	@Resource
	private ApprovalRecordMapper approvalRecordDao;
	@Resource 
	private RequestMapper requestDao;
	@Resource
	private RequestReportMapper requestReportDao;

	private LinkedHashMap<String, Employee> employeeTypeMap;
	
	/**
	 * 员工信息对接
	 */
	@Override
	public void saveEmployeeMain(List<EmployeeMainBean> employeeMainBeanList) {
		employeeTypeMap = new LinkedHashMap<String, Employee>();
		
		// 设置时间格式
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		// 获取人员表数据库中最小时间
		Date employeeFromDate = employeeExtDao.selectEmployeeMainFromDate();
		// 获取人员表数据库信息
		List<Employee> employeeList = employeeDao.selectByExample(new EmployeeExample());
		LinkedHashMap<String, Employee> employeeMap = new LinkedHashMap<String, Employee>();
		
		for (int ei = 0; ei < employeeList.size(); ei++) {
			employeeMap.put(employeeList.get(ei).getEmployeeNo(), employeeList.get(ei));
		}

		// 获取部门表数据库信息
		List<Department> departmentList = departmentDao.selectByExample(new DepartmentExample());
		LinkedHashMap<String, Department> departmentMap = new LinkedHashMap<String, Department>();
		for (int di = 0; di < departmentList.size(); di++) {
			departmentMap.put(departmentList.get(di).getDepartmentCode(), departmentList.get(di));
		}

		// 获取岗位表数据库信息
		List<Role> roleList = roleDao.selectByExample(new RoleExample());
		LinkedHashMap<String, Role> roleMap = new LinkedHashMap<String, Role>();
		for (int i = 0; i < roleList.size(); i++) {
			roleMap.put(roleList.get(i).getRoleCode(), roleList.get(i));
		}

		// 获取公司表数据库信息
		List<Corporation> corporationList = corporationDao.selectByExample(new CorporationExample());
		LinkedHashMap<String, Corporation> corporationMap = new LinkedHashMap<String, Corporation>();
		for (int i = 0; i < corporationList.size(); i++) {
			corporationMap.put(corporationList.get(i).getCorporationCode(), corporationList.get(i));
		}

		// 获取员工部门表数据库信息
		List<EmployeeDepartment> employeeDepartmentList = employeeDepartmentDao
				.selectByExample(new EmployeeDepartmentExample());
		LinkedHashMap<String, EmployeeDepartment> employeeDepartmentMap = new LinkedHashMap<String, EmployeeDepartment>();
		for (int edi = 0; edi < employeeDepartmentList.size(); edi++) {
			employeeDepartmentMap.put(employeeDepartmentList.get(edi).getEmployeeId() + "#"
					+ employeeDepartmentList.get(edi).getDepartmentId(), employeeDepartmentList.get(edi));
		}

		// 获取员工岗位表数据库信息
		List<EmployeeRole> employeeRoleList = employeeRoleDao.selectByExample(new EmployeeRoleExample());
		LinkedHashMap<String, EmployeeRole> employeeRoleMap = new LinkedHashMap<String, EmployeeRole>();
		for (int eri = 0; eri < employeeRoleList.size(); eri++) {
			employeeRoleMap.put(employeeRoleList.get(eri).getEmployeeId() + "#" + employeeRoleList.get(eri).getRoleId(),
					employeeRoleList.get(eri));
		}

		// 获取员工公司表数据库信息
		List<EmployeeCorporation> employeeCorporationList = employeeCorporationDao
				.selectByExample(new EmployeeCorporationExample());
		LinkedHashMap<String, EmployeeCorporation> employeeCorporationMap = new LinkedHashMap<String, EmployeeCorporation>();
		for (int i = 0; i < employeeCorporationList.size(); i++) {
			employeeCorporationMap.put(employeeCorporationList.get(i).getEmployeeId() + "#"
					+ employeeCorporationList.get(i).getCorporationId(), employeeCorporationList.get(i));
		}

		// 遍历主数据信息
		for (int i = 0; i < employeeMainBeanList.size(); i++) {
			EmployeeMainBean employeeMainBean = employeeMainBeanList.get(i);
			Employee employee = employeeMap.get(employeeMainBean.getEmployeeCode());
			if (employee != null) {
				//操作区分：7 表示删除员工信息
				if(StringUtils.isNotBlank(employeeMainBean.getActionFlag())) {
					if(employeeMainBean.getActionFlag().equals("7")) {
						Integer employeeId = employee.getEmployeeId();
						//入职日期减去当前日期10天范围内删除
						if(ToolUtils.differentDays(employeeMainBean.getJoinedDate(),ToolUtils.dateToStr(new Date()))<=10){
							//删除员工与公司关系表
							EmployeeCorporationExample employeeCorporationExample = new EmployeeCorporationExample();
							employeeCorporationExample.createCriteria().andEmployeeIdEqualTo(employeeId);
							employeeCorporationDao.deleteByExample(employeeCorporationExample);
							
							//删除员工与部门关系表
							EmployeeDepartmentExample employeeDepartmentExample = new EmployeeDepartmentExample();
							employeeDepartmentExample.createCriteria().andEmployeeIdEqualTo(employeeId);
							employeeDepartmentDao.deleteByExample(employeeDepartmentExample);
							
							//删除员工与岗位关系表	
							EmployeeRoleExample employeeRoleExample = new EmployeeRoleExample();
							employeeRoleExample.createCriteria().andEmployeeIdEqualTo(employeeId);
							employeeRoleDao.deleteByExample(employeeRoleExample);
							
							//删除员工班次表
							EmployeeSchedulExample employeeSchedulExample = new EmployeeSchedulExample();
							employeeSchedulExample.createCriteria().andEmployeeIdEqualTo(employeeId);
							employeeSchedulDao.deleteByExample(employeeSchedulExample);
							
							//删除特殊情况和人员关系表
							EmployeeSpecialExample employeeSpecialExample = new EmployeeSpecialExample();
							employeeSpecialExample.createCriteria().andEmployeeIdEqualTo(employeeId);
							employeeSpecialDao.deleteByExample(employeeSpecialExample);
							
							//删除人员表
							UserExample userExample = new UserExample();
							userExample.createCriteria().andEmployeeIdEqualTo(employeeId);
							userDao.deleteByExample(userExample);
							
							//删除员工登录记录表
							UserLoginExample userLoginExample=new UserLoginExample();
							userLoginExample.createCriteria().andEmployeeIdEqualTo(employeeId);
							userLoginDao.deleteByExample(userLoginExample);
							
							//删除员工休假余额表
							FurloughBalanceExample furloughBalanceExample=new FurloughBalanceExample();
							furloughBalanceExample.createCriteria().andEmployeeIdEqualTo(employeeId);
							furloughBalanceDao.deleteByExample(furloughBalanceExample);
							
							//删除哺乳假
							LactationExample lactationExample=new LactationExample();
							lactationExample.createCriteria().andEmployeeIdEqualTo(employeeId);
							lactationDao.deleteByExample(lactationExample);
							
							//删除考勤信息报表
							AttendanceReportExample attendanceReportExample=new AttendanceReportExample();
							attendanceReportExample.createCriteria().andEmployeeIdEqualTo(employeeId);
							attendanceReportDao.deleteByExample(attendanceReportExample);
							
							//删除申请权限设置表
							RequestAuthorityExample requestAuthorityExample=new RequestAuthorityExample();
							requestAuthorityExample.createCriteria().andEmployeeIdEqualTo(employeeId);
							requestAuthorityDao.deleteByExample(requestAuthorityExample);
							
							//查询考勤补签表
							RetroactiveExample retroactiveExample=new RetroactiveExample();
							retroactiveExample.createCriteria().andEmployeeIdEqualTo(employeeId);
							List<Retroactive> retroactiveList=retroactiveDao.selectByExample(retroactiveExample);
							List<Integer> retroactiveIdList=new ArrayList<Integer>();
							for(int ri=0;ri<retroactiveList.size();ri++) {
								retroactiveIdList.add(retroactiveList.get(ri).getRetroactiveId());
							}
							//删除审批记录表-补签信息
							if(retroactiveIdList.size()>0) {
								ApprovalRecordExample approvalRecordExample=new ApprovalRecordExample();
								approvalRecordExample.createCriteria().andRetroactiveIdIn(retroactiveIdList);
								approvalRecordDao.deleteByExample(approvalRecordExample);
							}
							//删除考勤补签表
							retroactiveDao.deleteByExample(retroactiveExample);
							
							//删除申请纤细表
							RequestReportExample requestReportExample=new RequestReportExample();
							requestReportExample.createCriteria().andEmployeeIdEqualTo(employeeId);
							requestReportDao.deleteByExample(requestReportExample);
							
							//查询申请表
							RequestExample requestExample=new RequestExample();
							requestExample.createCriteria().andEmployeeIdEqualTo(employeeId);
						    List<Request> requestList=requestDao.selectByExample(requestExample);
						    List<Integer> requestIdList=new ArrayList<Integer>();
						    for(int ri=0;ri<requestList.size();ri++) {
						    	requestIdList.add(requestList.get(ri).getRequestId());
						    }
						    //删除审批记录表-申请信息
						    if(requestIdList.size()>0) {
						    	ApprovalRecordExample approvalRecordExample=new ApprovalRecordExample();
								approvalRecordExample.createCriteria().andRequestIdIn(requestIdList);
								approvalRecordDao.deleteByExample(approvalRecordExample);
						    }
						    //删除申请表			    
							requestDao.deleteByExample(requestExample);
							
							//删除考勤表
							AttendanceExample attendanceExample = new AttendanceExample();
							attendanceExample.createCriteria().andEmployeeIdEqualTo(employeeId);
							attendanceDao.deleteByExample(attendanceExample);
							
							//删除员工表
							employeeDao.deleteByPrimaryKey(employeeId);
						}else{
							employee.setEmployeeIsSeparated(1);
							employee.setEmployeeSeparatedDate(ToolUtils.formatData(employeeMainBean.getJoinedDate()));
							employeeDao.updateByPrimaryKeySelective(employee);
						}
						continue;
					}
				}
				
				employee.setChineseName(employeeMainBean.getUserCname());
				employee.setEnglishName(employeeMainBean.getUserEname());
				
				employee.setOrganize1stCode(employeeMainBean.getOrganize1stCode());
				employee.setOrganize1stName(employeeMainBean.getOrganize1stName());
				employee.setOrganize2ndCode(employeeMainBean.getOrganize2ndCode());
				employee.setOrganize2ndName(employeeMainBean.getOrganize2ndName());
				employee.setOrganize3rdCode(employeeMainBean.getOrganize3rdCode());
				employee.setOrganize3rdName(employeeMainBean.getOrganize3rdName());
				employee.setOrganize4thCode(employeeMainBean.getOrganize4thCode());
				employee.setOrganize4thName(employeeMainBean.getOrganize4thName());
				employee.setProjectTeamCode(employeeMainBean.getProjectTeamCode());
				employee.setProjectTeamName(employeeMainBean.getProjectTeamName());
				
				// 判断性别
				if (StringUtils.isNotBlank(employeeMainBean.getSex())) {
					if(employeeMainBean.getSex().equals("0")) {
						employee.setSex(1);
					}
					if(employeeMainBean.getSex().equals("1")) {
						employee.setSex(2);
					}
				}
				
				//判断邮箱是否合法
				String regex = "[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?";
				Pattern p = Pattern.compile(regex);
				Matcher m = p.matcher(employeeMainBean.getCompanyEmail());
				if(m.matches()) {
					employee.setEmail(employeeMainBean.getCompanyEmail());
				}
				
				// 判断员工级别
				if (StringUtils.isNotBlank(employeeMainBean.getLevel())) {
					employee.setLevel(Integer.parseInt(employeeMainBean.getLevel()));
				}
				
				// 判断地区
				if (StringUtils.isNotBlank(employeeMainBean.getArea())) {
					if (employeeMainBean.getArea().equals("大连")) {
						employee.setRegionType(1);
					} else if (employeeMainBean.getArea().equals("北京")) {
						employee.setRegionType(2);
					} else if (employeeMainBean.getArea().equals("上海")) {
						employee.setRegionType(3);
					} else {
						employee.setRegionType(1);
					}
				}
				
				// 判断人员类别
				if (StringUtils.isNotBlank(employeeMainBean.getEmployeeFlag())) {
					if (employeeMainBean.getEmployeeFlag().contains("正式-")
							|| employeeMainBean.getEmployeeFlag().equals("正式")) {
						employee.setEmployeeType(1);
					} else if (employeeMainBean.getEmployeeFlag().equals("兼职")) {
						employee.setEmployeeType(3);
					} else {
						employee.setEmployeeType(4);
					}
				}else {
					employee.setEmployeeType(4);
				}
				
				// 2.协力 3.兼职 4.其他
				if (employee.getEmployeeType() == 2 || employee.getEmployeeType() == 3
						|| employee.getEmployeeType() == 4) {
					// 默认年假为无限大，不可使用年假
					String dataStr = "9999-01-01";
					employee.setAnnualLeaveDate(ToolUtils.formatData(dataStr));
				} else {
					// 根据员工级别判断年假可使用日期
					if (StringUtils.isNotBlank(employeeMainBean.getLevel())) {
						if (Integer.parseInt(employeeMainBean.getLevel()) <= 16) {
							String endDate = employeeMainBean.getTrialEndDate();
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
							if (StringUtils.isNotBlank(endDate)) {
								Date date;
								try {
									date = sdf.parse(endDate);
									Calendar cal = Calendar.getInstance();
									cal.setTime(date);
									cal.add(Calendar.DATE, 1);
									date = cal.getTime();
									employee.setAnnualLeaveDate(date);
								} catch (ParseException e) {
									e.printStackTrace();
								}
							}
						}
						if (Integer.parseInt(employeeMainBean.getLevel()) >= 17) {
							String joinedDate = employeeMainBean.getJoinedDate();
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
							if (StringUtils.isNotBlank(joinedDate)) {
								Date date;
								try {
									date = sdf.parse(joinedDate);
									Calendar cal = Calendar.getInstance();
									cal.setTime(date);
									cal.add(Calendar.MONTH, 2);
									date = cal.getTime();
									employee.setAnnualLeaveDate(date);
								} catch (ParseException e) {
									e.printStackTrace();
								}
							}
						}
						//设置免签类型为-允许免签
//						if(Integer.parseInt(employeeMainBean.getLevel()) >= 19)	{
//							employee.setIsVisaWaiver(1);
//						}
					}
				}
				
				try {
					// 转换首次工作时间
					if (StringUtils.isNotBlank(employeeMainBean.getParticipationDate())) {
						employee.setFirstDate(dateFormat.parse(employeeMainBean.getParticipationDate().trim()));
					}
					// 转换入职日期
					if (StringUtils.isNotBlank(employeeMainBean.getJoinedDate())) {
						employee.setEntryDate(dateFormat.parse(employeeMainBean.getJoinedDate().trim()));
					}
					// 判断离职状态
					if (StringUtils.isNotBlank(employeeMainBean.getEmployeeStatus())) {
						if (employeeMainBean.getEmployeeStatus().equals("离职")) {
							employee.setEmployeeIsSeparated(1);
							if (StringUtils.isBlank(employeeMainBean.getLeaveDate())) {
								employee.setEmployeeSeparatedDate(new Date());
							} else {
								employee.setEmployeeSeparatedDate(dateFormat.parse(employeeMainBean.getLeaveDate().trim()));
							}
						}else {
							employee.setEmployeeIsSeparated(0);
						}
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
				
				employee.setN1empCode(employeeMainBean.getN1empCode());
				employee.setN1empName(employeeMainBean.getN1empName());
				employee.setN2empCode(employeeMainBean.getN2empCode());
				employee.setN2empName(employeeMainBean.getN2empName());
				employee.setUpdateTime(new Date());
				
				employeeDao.updateByPrimaryKeySelective(employee);
				
				//判断如果启动时，离职日期更改为null
				if(employee.getEmployeeIsSeparated()!=null
						&& employee.getEmployeeIsSeparated()==0
						&& employee.getEmployeeSeparatedDate()!=null) {
					employeeExtDao.updateByEmployeeId(employee.getEmployeeId());
				}
				
				// 处理员工与部门关系表
				Department department = departmentMap.get(employeeMainBean.getDeptCode());
				if (department != null) {
					String key = employee.getEmployeeId() + "#" + department.getDepartmentId();
					EmployeeDepartment employeeDepartment = employeeDepartmentMap.get(key);
					if (employeeDepartment == null) {
						EmployeeDepartmentExample employeeDepartmentExample = new EmployeeDepartmentExample();
						employeeDepartmentExample.createCriteria().andEmployeeIdEqualTo(employee.getEmployeeId());
						employeeDepartmentDao.deleteByExample(employeeDepartmentExample);
						
						employeeDepartment = new EmployeeDepartment();
						employeeDepartment.setEmployeeId(employee.getEmployeeId());
						employeeDepartment.setDepartmentId(department.getDepartmentId());
						employeeDepartment.setFromDate(employeeFromDate);
						employeeDepartmentDao.insertSelective(employeeDepartment);
					}
				}
				
				//删除所有岗位
				EmployeeRoleExample employeeRoleExample = new EmployeeRoleExample();
				employeeRoleExample.createCriteria().andEmployeeIdEqualTo(employee.getEmployeeId());
				employeeRoleDao.deleteByExample(employeeRoleExample);
				
				// 处理员工与岗位关系表
				Role role = roleMap.get(employeeMainBean.getQuartersCode());
				if (role != null) {
					//增加主岗位
					EmployeeRole employeeRole = new EmployeeRole();
					employeeRole.setEmployeeId(employee.getEmployeeId());
					employeeRole.setRoleId(role.getRoleId());
					employeeRole.setFromDate(employeeFromDate);
					employeeRole.setIsRole(1);
					employeeRoleDao.insertSelective(employeeRole);
					
					Integer roleId = role.getRoleId();
					String key=employee.getEmployeeId()+"#"+roleId;
					employeeTypeMap.put(key,employee);
				}
				
				//增加兼职岗位1
				this.saveRole(employeeMainBean.getQuarters1Code(),roleMap,employee, employeeFromDate);
				
				//增加兼职岗位2
				this.saveRole(employeeMainBean.getQuarters2Code(),roleMap,employee, employeeFromDate);
				
				//增加兼职岗位3
				this.saveRole(employeeMainBean.getQuarters3Code(),roleMap,employee, employeeFromDate);
				
				//增加兼职岗位4
				this.saveRole(employeeMainBean.getQuarters4Code(),roleMap,employee, employeeFromDate);
				
				//增加兼职岗位5
				this.saveRole(employeeMainBean.getQuarters5Code(),roleMap,employee, employeeFromDate);
				
				//增加兼职岗位6
				this.saveRole(employeeMainBean.getQuarters6Code(),roleMap,employee, employeeFromDate);
				
				//增加兼职岗位7
				this.saveRole(employeeMainBean.getQuarters7Code(),roleMap,employee, employeeFromDate);
				
				//增加兼职岗8
				this.saveRole(employeeMainBean.getQuarters8Code(),roleMap,employee, employeeFromDate);
				
				//增加兼职岗9
				this.saveRole(employeeMainBean.getQuarters9Code(),roleMap,employee, employeeFromDate);
				
				//增加兼职岗10
				this.saveRole(employeeMainBean.getQuarters10Code(),roleMap,employee, employeeFromDate);
				
				// 处理员工与公司关系表
				Corporation corporation = corporationMap.get(employeeMainBean.getOrganize1stCode());
				if (corporation != null) {
					String key = employee.getEmployeeId() + "#" + corporation.getCorporationId();
					EmployeeCorporation employeeCorporation = employeeCorporationMap.get(key);
					// 如果信息有变化 则查询到的结果为空
					if (employeeCorporation == null) {
						EmployeeCorporationExample employeeCorporationExample = new EmployeeCorporationExample();
						employeeCorporationExample.createCriteria().andEmployeeIdEqualTo(employee.getEmployeeId())
						.andIsCorporationEqualTo(0);
						employeeCorporationDao.deleteByExample(employeeCorporationExample);
						
						employeeCorporation = new EmployeeCorporation();
						employeeCorporation.setEmployeeId(employee.getEmployeeId());
						employeeCorporation.setCorporationId(corporation.getCorporationId());
						employeeCorporation.setFromDate(employeeFromDate);
						employeeCorporation.setIsCorporation(0);
						employeeCorporation.setIsApproval(0);
						employeeCorporationDao.insertSelective(employeeCorporation);
					}
				}
				
			} else {	
				if (StringUtils.isNotBlank(employeeMainBean.getOpenStatus())) {
					if (!employeeMainBean.getOpenStatus().equals("3")) {
						// 如用户为新增 添加员工表
						employee = new Employee();
						employee.setEmployeeNo(employeeMainBean.getEmployeeCode());
						employee.setChineseName(employeeMainBean.getUserCname());
						employee.setEnglishName(employeeMainBean.getUserEname());
						
						employee.setOrganize1stCode(employeeMainBean.getOrganize1stCode());
						employee.setOrganize1stName(employeeMainBean.getOrganize1stName());
						employee.setOrganize2ndCode(employeeMainBean.getOrganize2ndCode());
						employee.setOrganize2ndName(employeeMainBean.getOrganize2ndName());
						employee.setOrganize3rdCode(employeeMainBean.getOrganize3rdCode());
						employee.setOrganize3rdName(employeeMainBean.getOrganize3rdName());
						employee.setOrganize4thCode(employeeMainBean.getOrganize4thCode());
						employee.setOrganize4thName(employeeMainBean.getOrganize4thName());
						employee.setProjectTeamCode(employeeMainBean.getProjectTeamCode());
						employee.setProjectTeamName(employeeMainBean.getProjectTeamName());
						
						// 判断性别
						if (StringUtils.isNotBlank(employeeMainBean.getSex())) {
							if(employeeMainBean.getSex().equals("0")) {
								employee.setSex(1);
							}
							if(employeeMainBean.getSex().equals("1")) {
								employee.setSex(2);
							}
						}
						//判断邮箱是否合法
						String regex = "[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?";
						Pattern p = Pattern.compile(regex);
						Matcher m = p.matcher(employeeMainBean.getCompanyEmail());
						if(m.matches()) {
							employee.setEmail(employeeMainBean.getCompanyEmail());
						}

						
						if (StringUtils.isNotBlank(employeeMainBean.getLevel())) {
							employee.setLevel(Integer.parseInt(employeeMainBean.getLevel()));
						}

						// 开始日期
						employee.setFromDate(employeeFromDate);
						// 新增员工类别
						employee.setEmployeeCategory(1);

						// 判断地区
						if (StringUtils.isNotBlank(employeeMainBean.getArea())) {
							if (employeeMainBean.getArea().equals("大连")) {
								employee.setRegionType(1);
							} else if (employeeMainBean.getArea().equals("北京")) {
								employee.setRegionType(2);
							} else if (employeeMainBean.getArea().equals("上海")) {
								employee.setRegionType(3);
							} else {
								employee.setRegionType(1);
							}
						}

						try {
							// 转换首次工作时间
							if (StringUtils.isNotBlank(employeeMainBean.getParticipationDate())) {
								employee.setFirstDate(dateFormat.parse(employeeMainBean.getParticipationDate().trim()));
							}

							// 转换入职日期
							if (StringUtils.isNotBlank(employeeMainBean.getJoinedDate())) {
								employee.setEntryDate(dateFormat.parse(employeeMainBean.getJoinedDate().trim()));
							}

							// 判断离职状态
							if (StringUtils.isNotBlank(employeeMainBean.getEmployeeStatus())) {
								if (employeeMainBean.getEmployeeStatus().equals("离职")) {
									employee.setEmployeeIsSeparated(1);
									if (StringUtils.isBlank(employeeMainBean.getLeaveDate())) {
										employee.setEmployeeSeparatedDate(new Date());
									} else {
										employee.setEmployeeSeparatedDate(
												dateFormat.parse(employeeMainBean.getLeaveDate().trim()));
									}
								}
							}
							
						} catch (ParseException e) {
							e.printStackTrace();
						}

						// 判断人员类别
						if (StringUtils.isNotBlank(employeeMainBean.getEmployeeFlag())) {
							if (employeeMainBean.getEmployeeFlag().contains("正式-")
									|| employeeMainBean.getEmployeeFlag().equals("正式")) {
								employee.setEmployeeType(1);
							} else if (employeeMainBean.getEmployeeFlag().equals("兼职")) {
								employee.setEmployeeType(3);
							} else {
								employee.setEmployeeType(4);
							}
						}else {
							employee.setEmployeeType(4);
						}

						
						
						// 2.协力 3.兼职 4.其他
						if (employee.getEmployeeType() == 2 || employee.getEmployeeType() == 3
								|| employee.getEmployeeType() == 4) {
							// 默认年假为无限大，不可使用年假
							String dataStr = "9999-01-01";
							employee.setAnnualLeaveDate(ToolUtils.formatData(dataStr));
						} else {
							// 根据员工级别判断年假可使用日期
							if (StringUtils.isNotBlank(employeeMainBean.getLevel())) {
								if (Integer.parseInt(employeeMainBean.getLevel()) <= 16) {
									String endDate = employeeMainBean.getTrialEndDate();
									SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
									if (StringUtils.isNotBlank(endDate)) {
										Date date;
										try {
											date = sdf.parse(endDate);
											Calendar cal = Calendar.getInstance();
											cal.setTime(date);
											cal.add(Calendar.DATE, 1);
											date = cal.getTime();
											employee.setAnnualLeaveDate(date);
										} catch (ParseException e) {
											e.printStackTrace();
										}
									}
								}
								if (Integer.parseInt(employeeMainBean.getLevel()) >= 17) {
									String joinedDate = employeeMainBean.getJoinedDate();
									SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
									if (StringUtils.isNotBlank(joinedDate)) {
										Date date;
										try {
											date = sdf.parse(joinedDate);
											Calendar cal = Calendar.getInstance();
											cal.setTime(date);
											cal.add(Calendar.MONTH, 2);
											date = cal.getTime();
											employee.setAnnualLeaveDate(date);
										} catch (ParseException e) {
											e.printStackTrace();
										}
									}
								}
								//设置免签类型为-允许免签
								if(Integer.parseInt(employeeMainBean.getLevel()) >= 19)	{
									employee.setIsVisaWaiver(1);
								}
							}
						}

						employee.setN1empCode(employeeMainBean.getN1empCode());
						employee.setN1empName(employeeMainBean.getN1empName());
						employee.setN2empCode(employeeMainBean.getN2empCode());
						employee.setN2empName(employeeMainBean.getN2empName());
						employeeDao.insertSelective(employee);

						//将新增员工信息存入Map
						employeeMap.put(employee.getEmployeeNo(), employee);
						
						// 如果为新增用户 添加班次表
						EmployeeSchedul employeeSchedul = new EmployeeSchedul();
						employeeSchedul.setEmployeeId(employee.getEmployeeId());
						employeeSchedul.setSwId(1);
						employeeSchedul.setPunchTimeId(1);
						String thruDate = "9999-01-01";
						employeeSchedul.setThruDate(ToolUtils.formatData(thruDate));
						employeeSchedul.setFromDate(employeeSchedulExtDao.selectFromDateMin());
						employeeSchedulDao.insertSelective(employeeSchedul);

						// 如用户为新增 添加User表
						User user = new User();
						user.setEmployeeId(employee.getEmployeeId());
						MD5Util md5 = new MD5Util();
						String mdPassWord = md5.getMD5ofStr(AppConstant.PASSWORD);
						user.setPassword(mdPassWord);
						user.setUsername(employee.getEmployeeNo());
						user.setPrivilegeGroupId(2);
						user.setFromDate(employeeFromDate);
						userDao.insertSelective(user);

						// 处理员工与部门关系表
						Department department = departmentMap.get(employeeMainBean.getDeptCode());
						if (department != null) {
							Integer departmentId = department.getDepartmentId();
							EmployeeDepartment employeeDepartment = new EmployeeDepartment();
							employeeDepartment.setEmployeeId(employee.getEmployeeId());
							employeeDepartment.setDepartmentId(departmentId);
							employeeDepartment.setFromDate(employeeFromDate);
							employeeDepartmentDao.insertSelective(employeeDepartment);
						}

						// 处理员工与岗位关系表
						Role role = roleMap.get(employeeMainBean.getQuartersCode());
						if (role != null) {
							Integer roleId = role.getRoleId();
							EmployeeRole employeeRole = new EmployeeRole();
							employeeRole.setEmployeeId(employee.getEmployeeId());
							employeeRole.setRoleId(roleId);
							employeeRole.setFromDate(employeeFromDate);
							employeeRole.setIsRole(1);
							employeeRoleDao.insertSelective(employeeRole);						
						}
						
						//判断、保存兼职岗位1
						this.saveRole(employeeMainBean.getQuarters1Code(),roleMap,employee, employeeFromDate);
						
						//判断、保存兼职岗位2
						this.saveRole(employeeMainBean.getQuarters2Code(),roleMap,employee, employeeFromDate);
						
						//判断、保存兼职岗位3
						this.saveRole(employeeMainBean.getQuarters3Code(),roleMap,employee, employeeFromDate);
						
						//判断、保存兼职岗位4
						this.saveRole(employeeMainBean.getQuarters4Code(),roleMap,employee, employeeFromDate);
						
						//判断、保存兼职岗位5
						this.saveRole(employeeMainBean.getQuarters5Code(),roleMap,employee, employeeFromDate);
						
						//判断、保存兼职岗位6
						this.saveRole(employeeMainBean.getQuarters6Code(),roleMap,employee, employeeFromDate);
						
						//判断、保存兼职岗位7
						this.saveRole(employeeMainBean.getQuarters7Code(),roleMap,employee, employeeFromDate);
						
						//判断、保存兼职岗位8
						this.saveRole(employeeMainBean.getQuarters8Code(),roleMap,employee, employeeFromDate);
						
						//判断、保存兼职岗位9
						this.saveRole(employeeMainBean.getQuarters9Code(),roleMap,employee, employeeFromDate);
						
						//判断、保存兼职岗位10
						this.saveRole(employeeMainBean.getQuarters10Code(),roleMap,employee, employeeFromDate);
						
						// 处理员工与公司关系表
						Corporation corporation = corporationMap.get(employeeMainBean.getOrganize1stCode());
						if (corporation != null) {
							Integer corporationId = corporation.getCorporationId();
							EmployeeCorporation employeeCorporation = new EmployeeCorporation();
							employeeCorporation.setEmployeeId(employee.getEmployeeId());
							employeeCorporation.setCorporationId(corporationId);
							employeeCorporation.setFromDate(employeeFromDate);
							employeeCorporation.setIsApproval(0);
							employeeCorporation.setIsCorporation(0);
							employeeCorporationDao.insertSelective(employeeCorporation);
						}
					}
				}
			}
		}
	}
	
	/**
	 * 处理兼职岗位信息
	 * @param QuartersCode
	 * @param roleMap
	 * @param employee
	 * @param employeeFromDate
	 */
	private void saveRole(String quartersCode,LinkedHashMap<String, Role> roleMap,Employee employee,Date employeeFromDate) {
		if(StringUtils.isNotBlank(quartersCode)) {
			Role role = roleMap.get(quartersCode);
			if(role != null) {
				Integer roleId = role.getRoleId();
				String key=employee.getEmployeeId()+"#"+roleId;
				if(employeeTypeMap.get(key) == null) {
					EmployeeRole employeeRole = new EmployeeRole();
					employeeRole.setEmployeeId(employee.getEmployeeId());
					employeeRole.setRoleId(roleId);
					employeeRole.setFromDate(employeeFromDate);
					employeeRole.setIsRole(0);
					employeeRoleDao.insertSelective(employeeRole);
					employeeTypeMap.put(key,employee);
				}
			}
		}
	}
	
	
}
